package descentFly.chips
{
	import UIFree.ObjectEvent;
	
	import descentFly.data.df_fields;
	import descentFly.df_optionsObject;
	import descentFly.df_space;
	import descentFly.df_spaceObject;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import space.sp_utils;
	
	public class df_weapont extends df_optionsObject {
		public static const CHANGE_AMMO: String = 'CHANGE_AMMO';
		public static const EMPTY_AMMO: String = 'EMPTY_AMMO';
		
		public static const FIELD_AMMOLIMIT: String = 'ammoLimit';
		public static const DEFAULT_AMMOLIMIT: int = 0;
		
		private var _chip		: df_chip;
		private var _ammo		: uint;
		
		public function df_weapont(a_chip: df_chip, a_options: Object) {
			sp_utils.checkParam(a_options, FIELD_AMMOLIMIT, DEFAULT_AMMOLIMIT);
			sp_utils.checkParam(a_options, df_fields.FIELD_ID, 0);
			super(a_options);
			_ammo		= 0;
			_chip 		= a_chip;
			_chip.addWeapont(this);
			_chip.addEventListener(df_chip.CHANGEWEAPONT, doChipChangeWeapont);
		}
		
		override protected function removeEvents():void {
			_chip.removeEventListener(df_chip.CHANGEWEAPONT, doChipChangeWeapont);
			super.removeEvents();
		}
		
		protected function doChipChangeWeapont(e: Event): void {
			if (isFire) {
				fire(false);
				if (_chip.currentWeapont) _chip.currentWeapont.fire(true);
			}
		}
		
		public function get ammo(): uint {
			return _ammo;
		}
		
		public function get ammoLimit(): uint {
			return options[FIELD_AMMOLIMIT];
		}
		
		public function set ammo(a_ammo: uint): void {
			if (a_ammo < 0) a_ammo = 0;
			_ammo = a_ammo;
			dispatchEvent(new Event(CHANGE_AMMO));
			if ((_ammo <= 0) && limited) emptyAmmo();
		}
		
		protected function emptyAmmo(): void {
			dispatchEvent(new Event(EMPTY_AMMO));
		}
		
		public function get limited(): Boolean {
			return ammoLimit > 0;
		}
		
		protected function get Space(): df_space {
			return _chip.space;
		}
		
		protected function get chip(): df_chip {
			return _chip;
		}
		
		public function fire(a_fire: Boolean): Boolean {
			if (a_fire != isFire) {
				if (a_fire) {
					if (checkLimit()) {
						setFire(a_fire);
						return true;
					}
				} else {
					setFire(a_fire);
					return true;
				}
			}
			return false;
		}
		
		protected function checkLimit(): Boolean {
			return true;
		}
		
		protected function setFire(a_fire: Boolean): void {
			
		}
		
		public function get isFire(): Boolean {
			return false;
		}
	}
}